from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from rest_framework import mixins
from rest_framework.response import Response
from .sers import *
from goodsapp.sers import CategorySer


# 开发 添加规格的接口
class SpecifyView(APIView):

    def post(self, request):
        ser = SpecifySer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"msg": "添加成功", "code": 200})
        else:
            print(ser.errors)

            return Response({"msg": "添加失败", "code": 400})


# 开发 添加商品的接口
class GoodsView(GenericAPIView, mixins.CreateModelMixin):
    serializer_class = GoodsSer

    def post(self, request):

        try:
            self.create(request)
            return Response({"msg": "添加成功", "code": 200})
        except Exception as e:
            print(e)
            return Response({"msg": "添加失败", "code": 400})


# 定义一个接口，根据 一级分类 可以获取到对应的二级分类
class CategoryViewByPidView(APIView):

    def get(self, request):
        # 根据父id去 获取对应的子分类
        pid = request.GET.get("pid")
        # 找到了子分类
        queryset = Category.objects.filter(parent_id=pid)
        ser = CategorySer(queryset, many=True)
        return Response(ser.data)


from qiniu import Auth
from h2004a_md.settings import AK, SK


class QiniuTokenView(APIView):

    def get(self, request):
        # 1、初始化 SKD
        auth = Auth(AK, SK)
        # 空间名
        bucket = "h2004a"
        # 2、
        token = auth.upload_token(bucket)
        return Response({"token": token})
     